package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Cheque;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.Date;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Timoshenko Alexander 18.09.2008 : 0:17:55
 */
public class ChequeDao extends BaseDaoObject<Cheque> {
    public Cheque getByKey(Serializable key) {
        return (Cheque) getHibernateTemplate().get(Cheque.class, key);
    }

    public Set<Cheque> getByDate(final Date date, final String username, final String employeeId, final String customerId) {
        return (Set<Cheque>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                StringBuilder query = new StringBuilder("select cheque from Cheque cheque, Login login LEFT JOIN cheque.transactions trans where " +
                        "login.login = :username and cheque.location = login.location and cheque.creationDate = :date");

                if (!StringUtils.isBlank(employeeId)) {
                    query.append(" and trans.employee.id = :employeeId ");
                }
                if(!StringUtils.isBlank(customerId)){
                    query.append(" and cheque.customer.id = :customerId");
                }
                Query q = session.createQuery(query.toString())
                        .setParameter("username", username, Hibernate.STRING)
                        .setParameter("date", date, Hibernate.DATE);
                if (!StringUtils.isBlank(employeeId)) {
                    q.setParameter("employeeId", Long.valueOf(employeeId), Hibernate.LONG);
                }

                if(!StringUtils.isBlank(customerId)){
                    q.setParameter("customerId", Long.valueOf(customerId), Hibernate.LONG);
                }
                List<Cheque> result = q.list();
                return result == null || result.isEmpty() ? new HashSet<Cheque>() : new HashSet<Cheque>(result);
            }
        });
    }    

    public Cheque getByNumber(final String number){
        return (Cheque)getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List<Cheque> result = session.createQuery("from Cheque where number = :number")
                        .setParameter("number", number, Hibernate.STRING)
                        .list();
                return result == null || result.isEmpty()? null : result.get(0);
            }
        });
    }
}
